package edu.njust.httpmanager.utils;

import edu.njust.httpmanager.constance.SystemConstance;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;
import java.util.Map;

public class JwtUtil {

    /**
     * 存储多个数据
     * @param claims
     * @param expirationTime 有效期：毫秒
     * @return
     */
    public static String create(Map<String, Object> claims, long expirationTime) {
        Date now = new Date();
        Date expiryDate = new Date(now.getTime() + expirationTime * 3600 * 1000 * 24);

        return Jwts.builder()
                .setClaims(claims)
                .setExpiration(expiryDate)
                .signWith(SignatureAlgorithm.HS512, SystemConstance.JWT_SECRET)
                .compact();
    }

    /**
     * 有效期为 30 天的token
     * @param claims
     * @return
     */
    public static String create(Map<String, Object> claims) {
        Date now = new Date();
        Date expiryDate = new Date(now.getTime() + 3600L * 1000 * 24 * 30);

        return Jwts.builder()
                .setClaims(claims)
                .setExpiration(expiryDate)
                .signWith(SignatureAlgorithm.HS512, SystemConstance.JWT_SECRET)
                .compact();
    }

    /**
     * 解析token, 获取用户Id
     * @param token
     * @return
     */
    public static Long getId(String token) {
        Claims claims = getClaimsFromJwtToken(token);
        return (Long) claims.get("id");
    }

    public static Claims getClaimsFromJwtToken(String token) {
        Claims claims = Jwts.parser()
                .setSigningKey(SystemConstance.JWT_SECRET)
                .parseClaimsJws(token)
                .getBody();

        return claims;
    }

    public static boolean validateJwtToken(String token) {
        try {
            Jwts.parser().setSigningKey(SystemConstance.JWT_SECRET).parseClaimsJws(token);
            return true;
        } catch (Exception e) {
            // 处理校验失败的逻辑

        }
        return false;
    }
}
